<template>
  <div class="grab-task-manager">
    <!-- 任务列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>景点抓取任务管理</span>
          <el-button type="primary" @click="showCreateDialog" :icon="Plus">
            新建任务
          </el-button>
        </div>
      </template>

      <el-table :data="taskStore.tasks" :loading="taskStore.loading" style="width: 100%">
        <el-table-column prop="cityName" label="城市名称" width="150" />
        <el-table-column prop="keywords" label="景点关键词" min-width="120" />
        <el-table-column prop="totalExecuteCount" label="总执行次数" min-width="120" />
        <el-table-column prop="totalNewCount" label="新增数量" min-width="120" />
        <el-table-column prop="totalUpdateCount" label="更新数量" min-width="120" />
        <el-table-column prop="lastExecuteTime" label="最后执行时间" min-width="120" />
        <el-table-column label="操作" width="330" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                  size="small"
                  type="info"
                  @click="editTask(row)"
                  :icon="Edit"
              >
                编辑
              </el-button>
              <el-button
                  size="small"
                  type="primary"
                  @click="executeTask(row.id)"
                  :icon="CaretRight"
              >
                立即执行
              </el-button>
              <el-button
                  type="warning"
                  size="small"
                  :icon="Delete"
                  @click="deleteTask(row.id)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
        v-model="showTaskDialog"
        :title="editingTask ? '编辑任务' : '新建任务'"
        width="600px"
    >
      <el-form :model="taskForm" :rules="taskRules" ref="taskFormRef" label-width="120px">
        <el-form-item label="城市名称" prop="cityName">
          <el-input v-model="taskForm.cityName" placeholder="请输入城市名称，例如：北京、上海、天津..." />
        </el-form-item>
        <el-form-item label="景点关键词" prop="keywords">
          <el-input
              v-model="taskForm.keywords"
              type="textarea"
              :rows="2"
              placeholder="请输入景点关键词，可不填"
          />
        </el-form-item>
        <el-form-item label="页码设置" v-if="taskForm.keywords === ''">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="startPageIndex">
                <el-input-number
                    v-model="taskForm.startPageIndex"
                    :min="1"
                    :max="9"
                    placeholder="开始页码"
                    style="width: 100%"
                />
                <div class="form-item-tip">开始页码</div>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">
              <span style="line-height: 32px;">至</span>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="endPageIndex">
                <el-input-number
                    v-model="taskForm.endPageIndex"
                    :min="taskForm.startPageIndex || 1"
                    placeholder="结束页码"
                    style="width: 100%"
                />
                <div class="form-item-tip">结束页码（可选）</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <div class="form-help-text" style="text-align: center" v-if="taskForm.keywords === ''">
          <el-icon><InfoFilled /></el-icon>
          如果不填写结束页码，则只爬取开始页码的单页数据
        </div>
        <div class="form-help-text" style="text-align: center">
          <el-icon><WarningFilled /></el-icon>
          如果填写了景点关键词，则忽略页码设置，只获取该景点的数据
        </div>
        <div class="form-help-text" style="text-align: center">
          <el-icon><WarningFilled /></el-icon>
          如果填写了城市名称但未填写关键词，则获取该城市下所有景点的数据
        </div>
      </el-form>
      <template #footer>
        <el-button @click="showTaskDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTask" :loading="saving">
          {{ editingTask ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useGrabTaskStore } from '@/stores/grabTask'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  CaretRight,
  Delete,
  InfoFilled,
  WarningFilled
} from '@element-plus/icons-vue'

const taskStore = useGrabTaskStore()

// 对话框状态
const showTaskDialog = ref(false)
const editingTask = ref(null)
const saving = ref(false)

// 表单数据
const taskForm = reactive({
  cityName: '',
  keywords: '',
  startPageIndex: 1,
  endPageIndex: 10,
  pageSize: 20,
})

// 表单验证规则
const taskRules = {
  cityName: [
    { required: true, message: '请输入城市名称', trigger: 'blur' }
  ]
}

const taskFormRef = ref()

// 显示创建对话框
const showCreateDialog = () => {
  editingTask.value = null
  resetForm()
  showTaskDialog.value = true
}

// 编辑任务
const editTask = (task) => {
  editingTask.value = task
  Object.assign(taskForm, {
    cityName: task.cityName,
    keywords: task.keywords,
    startPageIndex: task.startPageIndex,
    endPageIndex: task.endPageIndex,
    pageSize: task.pageSize
  })
  showTaskDialog.value = true
}

// 保存任务
const saveTask = async () => {
  try {
    await taskFormRef.value.validate()

    saving.value = true

    if (editingTask.value) {
      await taskStore.updateTask(editingTask.value.id, taskForm)
      ElMessage.success('任务更新成功')
    } else {
      await taskStore.createTask(taskForm)
      ElMessage.success('任务创建成功')
    }

    showTaskDialog.value = false
  } catch (error) {
    console.error('保存任务失败:', error)
  } finally {
    saving.value = false
  }
}

// 立即执行任务
const executeTask = async (id) => {
  try {
    await ElMessageBox.confirm('确认立即执行该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await taskStore.executeTask(id)
    ElMessage.success('任务执行已启动')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('执行任务失败')
    }
  }
}

// 删除任务
const deleteTask = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该任务吗？删除后无法恢复。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await taskStore.deleteTask(id)
    ElMessage.success('任务删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(taskForm, {
    cityName: '',
    keywords: '',
    startPageIndex: 1,
    endPageIndex: 10,
    pageSize: 20,
  })
  taskFormRef.value?.clearValidate()
}

onMounted(() => {
  taskStore.fetchTasks()
})
</script>

<style scoped>
.grab-task-manager {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .text-center {
    text-align: center;
    line-height: 32px;
  }
}
</style>